package com.jic.member.impl.power;
import	java.util.ArrayList;

import java.util.Date;

import java.lang.Long;
import java.util.List;

import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.RestResult;
import com.jic.manager.api.manage.SysDeptApi;
import com.jic.member.common.util.BeanUtil;
import com.jic.member.entity.MememberLegalLogisticsIncrement;
import com.jic.member.entity.MememberLegalRuleAction;
import com.jic.member.entity.MememberLegalRuleLogistics;
import com.jic.member.entity.power.MegradeRule;
import com.jic.member.entity.power.MememberLegalRule;
import com.jic.member.entity.power.MevipRule;
import com.jic.member.enums.POWER_NO;
import com.jic.member.mapper.MememberLegalLogisticsIncrementMapper;
import com.jic.member.mapper.MememberLegalRuleActionMapper;
import com.jic.member.mapper.MememberLegalRuleLogisticsMapper;
import com.jic.member.mapper.power.MegradeRuleMapper;
import com.jic.member.mapper.power.MememberLegalRuleMapper;
import com.jic.member.mapper.power.MevipRuleMapper;
import com.jic.member.request.power.LegalLogisticsIncrement;
import com.jic.member.request.power.MememberLegalRuleRequest;
import com.jic.member.response.power.MememberLegalRuleResponse;
import com.jic.member.service.power.MememberLegalRuleService;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 会员等级管理-权益规则主表
 *
 * @author : zxl
 * @version : v1.0.0
 * @email :
 * @since : 2020-04-03 10:51:56
 */
@Service
public class MememberLegalRuleServiceImpl implements MememberLegalRuleService {

    @Resource
    private MememberLegalRuleMapper mememberLegalRuleMapper;
    @Resource
    private MememberLegalLogisticsIncrementMapper mememberLegalLogistics;//递增表
    @Resource
    private MememberLegalRuleLogisticsMapper mememberLegalRuleLogisticsMapper;//物流主表
    @Resource
    MememberLegalRuleActionMapper mememberLegalRuleActionMapper;
    @Resource
    MevipRuleMapper mevipRuleMapper;
    @Resource
    MegradeRuleMapper megradeRuleMapper;
    @Resource
    private SysDeptApi sysDeptApi;


    @Override
    public long insert(MememberLegalRule mememberLegalRule) {
        long flag = mememberLegalRuleMapper.insert(mememberLegalRule);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return mememberLegalRuleMapper.delete(id);
    }

    @Override
    public long update(MememberLegalRule mememberLegalRule) {
        return mememberLegalRuleMapper.update(mememberLegalRule);
    }

    @Override
    public MememberLegalRule queryByPrimaryKey(Long legalRuleId) {
        return mememberLegalRuleMapper.queryByPrimaryKey(legalRuleId);
    }

    @Override
    public List<MememberLegalRule> query(MememberLegalRule mememberLegalRule) {
        return mememberLegalRuleMapper.query(mememberLegalRule);
    }

    @Override
    public PageResult<MememberLegalRule> queryPage(MememberLegalRule mememberLegalRule, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        mememberLegalRule.setDeleteFlag(0);
        AdminOperate admin = mememberLegalRule.getAdminOperate();
        mememberLegalRule.setDeptId(admin.getDeptId());
        List<MememberLegalRule> list = mememberLegalRuleMapper.queryPage(startIndex, pageQuery.getLimit(), mememberLegalRule);
        long count = mememberLegalRuleMapper.queryPageCount(mememberLegalRule);
        list.forEach(items -> {
            RestResult<String> name = sysDeptApi.queryDeptNameById(items.getDeptId());
            items.setDeptId(admin.getDeptId());
            items.setDeptName(name.getData());
        });

        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public RestResult<Long> insertMemberLegal(MememberLegalRuleRequest form) {
        long flag = 0;
        RestResult result = new RestResult();
        AdminOperate admin = form.getAdminOperate();
        //保存方法
        if (form.getId() == null) {
            //主表插入 mem_member_legal_rule
            MememberLegalRule memberRequest = BeanUtil.copy(form, MememberLegalRule.class);
            MememberLegalRuleLogistics mememberLegalRuleLogistics = new MememberLegalRuleLogistics();
            MememberLegalLogisticsIncrement logistics = new MememberLegalLogisticsIncrement();
            MememberLegalRuleAction ruleAction = new MememberLegalRuleAction();
            //添加dept——id
            memberRequest.setDeptId(admin.getDeptId());
            mememberLegalRuleLogistics.setDeptId(admin.getDeptId());
            logistics.setDeptId(admin.getDeptId());
            ruleAction.setDeptId(admin.getDeptId());

            memberRequest.setCreator(admin.getOperator());
            memberRequest.setCreatorName(admin.getOperateName());
            memberRequest.setDeleteFlag(0);
            memberRequest.setCreateTime(new Date());
            flag = mememberLegalRuleMapper.insert(memberRequest);
            //购物 积分 活动 内容 服务 等级升级 (子账号数)
            if (POWER_NO.SHOPPING_NO.getName().equals(form.getLegalRuleType()) || POWER_NO.INTEGRAL_NO.getName().equals(form.getLegalRuleType())
                    || POWER_NO.ACTIVITY_NO.getName().equals(form.getLegalRuleType())
                    || POWER_NO.CONTENTL_NO.getName().equals(form.getLegalRuleType())
                    || POWER_NO.SERVICE_NO.getName().equals(form.getLegalRuleType())
                    || POWER_NO.GRADE_NO.getName().equals(form.getLegalRuleType())
                    || POWER_NO.CHILD_NO.getName().equals(form.getLegalRuleType())) {
                ruleAction.setCreator(admin.getOperator());
                ruleAction.setCreateTime(new Date());
                ruleAction.setCreatorName(admin.getOperateName());
                ruleAction.setDeleteFlag(0);
                ruleAction.setLegalRuleId(memberRequest.getId());
                ruleAction.setLegalRuleType(Integer.parseInt(form.getLegalRuleType()));
                ruleAction.setRuleValue(form.getRuleValue());
                ruleAction.setLegalRuleName(form.getLegalRuleName());
                mememberLegalRuleActionMapper.insert(ruleAction);

            } else {
                // 物流 插入 mem_member_legal_rule_logistics
                mememberLegalRuleLogistics.setCreator(admin.getOperator());
                mememberLegalRuleLogistics.setCreateTime(new Date());
                mememberLegalRuleLogistics.setCreatorName(admin.getOperateName());
                mememberLegalRuleLogistics.setDeleteFlag(0);
                mememberLegalRuleLogistics.setLegalRuleId(memberRequest.getId());
                mememberLegalRuleLogistics.setFreightMode(form.getFreightMode());
                mememberLegalRuleLogisticsMapper.insert(mememberLegalRuleLogistics);
                //如果是减运费
                if (form != null && form.getFreightMode() == 2) {
                    //插入 mem_member_legal_logistics_increment
                    List<LegalLogisticsIncrement> logisticsIncrement = form.getLogisticsIncrement();
                    logistics.setCreator(admin.getOperator());
                    logistics.setCreatorName(admin.getOperateName());
                    logistics.setDeleteFlag(0);
                    logistics.setCreateTime(new Date());
                    logistics.setLegalRuleId(memberRequest.getId());
                    logistics.setRuleLogisticsId(mememberLegalRuleLogistics.getId());
                    logisticsIncrement.forEach(items -> {
                        logistics.setSatisfyOrder(items.getSatisfyOrder());
                        logistics.setReductionMoney(items.getReductionMoney());
                        mememberLegalLogistics.insert(logistics);
                    });
                }

            }
            result.setData(memberRequest.getId());
            result.setCode("0000");
         //修改
        } else {
            //查询等级关联表
            MegradeRule megradeRule = new MegradeRule(){{
                setDeleteFlag(0);
                setLegalRuleId(form.getId());
            }};
            List<MegradeRule>megradeRuleResult = megradeRuleMapper.query(megradeRule);
            //查询Vip关联表
            MevipRule mevip = new MevipRule(){{
                setDeleteFlag(0);
                setLegalRuleId(form.getId());
            }};
            //主表修改mem_member_legal_rule
            MememberLegalRule memberRequest = BeanUtil.copy(form, MememberLegalRule.class);
            MememberLegalRuleAction ruleAction = new MememberLegalRuleAction();
            MememberLegalRuleLogistics mememberLegalRuleLogistics = new MememberLegalRuleLogistics();
            memberRequest.setUpdater(admin.getOperator());
            memberRequest.setUpdateTime(new Date());
            mememberLegalRuleMapper.update(memberRequest);
            //如果是购物 积分 活动 内容 服务 等级升级
            if (POWER_NO.SHOPPING_NO.getName().equals(form.getLegalRuleType()) || POWER_NO.INTEGRAL_NO.getName().equals(form.getLegalRuleType())
                    || POWER_NO.ACTIVITY_NO.getName().equals(form.getLegalRuleType())
                    || POWER_NO.CONTENTL_NO.getName().equals(form.getLegalRuleType())
                    || POWER_NO.SERVICE_NO.getName().equals(form.getLegalRuleType())
                    || POWER_NO.GRADE_NO.getName().equals(form.getLegalRuleType())
                    || POWER_NO.CHILD_NO.getName().equals(form.getLegalRuleType())) {
                ruleAction.setUpdator(admin.getOperator());
                ruleAction.setUpdateTime(new Date());
                ruleAction.setRuleValue(form.getRuleValue());
                ruleAction.setLegalRuleId(form.getId());
                ruleAction.setLegalRuleType(Integer.parseInt(form.getLegalRuleType()));
                mememberLegalRuleActionMapper.update(ruleAction);
                //物流服务修改
            }else {
                //查询之前的是‘免运费’还是‘减运费’
                MememberLegalRuleLogistics ruleLogistics = mememberLegalRuleLogisticsMapper.queryInfoByLegalRuleId(form.getId());
                if (null !=ruleLogistics){
                    if (ruleLogistics.getFreightMode().intValue()== 1 && form.getFreightMode().intValue() ==1){
                        return result;
                    }else if (ruleLogistics.getFreightMode().intValue()== 1 && form.getFreightMode().intValue() ==2){
                        //修改mem_member_legal_rule_logistics
                        mememberLegalRuleLogistics.setUpdater(admin.getOperator());
                        mememberLegalRuleLogistics.setUpdaterName(admin.getOperateName());
                        mememberLegalRuleLogistics.setFreightMode(2);
                        mememberLegalRuleLogistics.setId(ruleLogistics.getId());
                        mememberLegalRuleLogisticsMapper.update(mememberLegalRuleLogistics);
                        //插入 mem_member_legal_logistics_increment
                        List<LegalLogisticsIncrement> logisticsIncrement = form.getLogisticsIncrement();
                        MememberLegalLogisticsIncrement logistics = new MememberLegalLogisticsIncrement();
                        logistics.setCreator(admin.getOperator());
                        logistics.setCreatorName(admin.getOperateName());
                        logistics.setDeleteFlag(0);
                        logistics.setCreateTime(new Date());
                        logistics.setLegalRuleId(memberRequest.getId());
                        logistics.setRuleLogisticsId(ruleLogistics.getId());
                        logisticsIncrement.forEach(items -> {
                            logistics.setSatisfyOrder(items.getSatisfyOrder());
                            logistics.setReductionMoney(items.getReductionMoney());
                            mememberLegalLogistics.insert(logistics);
                        });
                    }else if ( ruleLogistics.getFreightMode().intValue()== 2 && form.getFreightMode().intValue() ==2){
                        //先删除后插入
                        mememberLegalLogistics.deleteByRuleLogisticsId(ruleLogistics.getId());
                        List<LegalLogisticsIncrement> logisticsIncrement = form.getLogisticsIncrement();
                        MememberLegalLogisticsIncrement logistics = new MememberLegalLogisticsIncrement();
                        logistics.setCreator(admin.getOperator());
                        logistics.setCreatorName(admin.getOperateName());
                        logistics.setDeleteFlag(0);
                        logistics.setCreateTime(new Date());
                        logistics.setLegalRuleId(form.getId());
                        logistics.setRuleLogisticsId(ruleLogistics.getId());
                        logisticsIncrement.forEach(items -> {
                            logistics.setSatisfyOrder(items.getSatisfyOrder());
                            logistics.setReductionMoney(items.getReductionMoney());
                            mememberLegalLogistics.insert(logistics);
                        });
                    }else if ( ruleLogistics.getFreightMode().intValue()== 2 && form.getFreightMode().intValue() ==1){
                        //先删除后修改
                        mememberLegalLogistics.deleteByRuleLogisticsId(ruleLogistics.getId());
                        MememberLegalRuleLogistics memLegalRuleLogistics= new MememberLegalRuleLogistics();
                        memLegalRuleLogistics.setUpdater(admin.getOperator());
                        memLegalRuleLogistics.setUpdateTime(new Date());
                        memLegalRuleLogistics.setFreightMode(1);
                        memLegalRuleLogistics.setLegalRuleId(form.getId());
                        mememberLegalRuleLogisticsMapper.updateByLegalRuleId(memLegalRuleLogistics);

                    }

                }

            }
            result.setCode("0000");
        }
        return result;
    }

    @Override
    public MememberLegalRuleResponse queryMemberPowerInfo(MememberLegalRuleRequest form) {
        MememberLegalRuleResponse mememberLegalRuleResponse=new MememberLegalRuleResponse();
        if (POWER_NO.SHOPPING_NO.getName().equals(form.getLegalRuleType()) || POWER_NO.INTEGRAL_NO.getName().equals(form.getLegalRuleType())
                || POWER_NO.ACTIVITY_NO.getName().equals(form.getLegalRuleType())
                || POWER_NO.CONTENTL_NO.getName().equals(form.getLegalRuleType())
                || POWER_NO.SERVICE_NO.getName().equals(form.getLegalRuleType())
                || POWER_NO.GRADE_NO.getName().equals(form.getLegalRuleType())
                || POWER_NO.CHILD_NO.getName().equals(form.getLegalRuleType())) {
            //根据legal_rule_id 和 legal_rule_type查询mem_member_legal_rule_action
            Integer legalRuleType = Integer.parseInt(form.getLegalRuleType());
            mememberLegalRuleResponse =mememberLegalRuleActionMapper.queryInfoByLegalRuleType(form.getId(), legalRuleType);

        }else {
            MememberLegalRuleLogistics  ruleLogistics = mememberLegalRuleLogisticsMapper.queryInfoByLegalRuleId(form.getId());
            if (null != ruleLogistics){
                if(ruleLogistics.getFreightMode()==1){
                    mememberLegalRuleResponse.setFreightMode(1);
                }else {
                    mememberLegalRuleResponse.setFreightMode(2);
                    MememberLegalLogisticsIncrement increment = new MememberLegalLogisticsIncrement(){{
                        setRuleLogisticsId(ruleLogistics.getId());
                        setDeleteFlag(0);
                    }};
                    List<MememberLegalLogisticsIncrement> incrementList=mememberLegalLogistics.query(increment);
                    List<LegalLogisticsIncrement> logisticsIncrement=new ArrayList<> ();
                    for(int i = 0; i <incrementList.size();i++){
                        LegalLogisticsIncrement logistics= new LegalLogisticsIncrement();
                        logistics.setId(incrementList.get(i).getId());
                        logistics.setSatisfyOrder(incrementList.get(i).getSatisfyOrder());
                        logistics.setReductionMoney(incrementList.get(i).getReductionMoney());
                        logisticsIncrement.add(logistics);
                    }
                    mememberLegalRuleResponse.setLogisticsIncrement(logisticsIncrement);
                }
            }

        }
        return mememberLegalRuleResponse;
    }

    @Override
    public RestResult<Long> deletMemberInfo(MememberLegalRuleRequest form) {
        RestResult result = new RestResult();
        //查询等级关联表
        MegradeRule megradeRule = new MegradeRule(){{
            setDeleteFlag(0);
            setLegalRuleId(form.getId());
            setDeptId(form.getAdminOperate().getDeptId());
        }};
        List<MegradeRule>megradeRuleResult = megradeRuleMapper.query(megradeRule);
        //查询Vip关联表
        MevipRule mevip = new MevipRule(){{
            setDeleteFlag(0);
            setLegalRuleId(form.getId());
            setDeptId(form.getAdminOperate().getDeptId());
        }};
        List<MevipRule>mevipResult = mevipRuleMapper.query(mevip);
        if (mevipResult.size()>0 || megradeRuleResult.size()>0){
            result.setMsg("该等级下已关联平台权益，请解除关联后再进行操作!");
            result.setCode("9999");
            return result;
        }
        if (POWER_NO.SHOPPING_NO.getName().equals(form.getLegalRuleType()) || POWER_NO.INTEGRAL_NO.getName().equals(form.getLegalRuleType())
                || POWER_NO.ACTIVITY_NO.getName().equals(form.getLegalRuleType())
                || POWER_NO.CONTENTL_NO.getName().equals(form.getLegalRuleType())
                || POWER_NO.SERVICE_NO.getName().equals(form.getLegalRuleType())
                || POWER_NO.GRADE_NO.getName().equals(form.getLegalRuleType())) {
            //先删除主表信息
            mememberLegalRuleMapper.delete(form.getId());
            //删除关联表信息
            mememberLegalRuleActionMapper.deleteByLegalRuleId(form.getId());
        }else {
            //先删除主表信息
            mememberLegalRuleMapper.delete(form.getId());
            MememberLegalRuleLogistics  ruleLogistics = mememberLegalRuleLogisticsMapper.queryInfoByLegalRuleId(form.getId());
            if (null !=ruleLogistics && ruleLogistics.getFreightMode()==1){
                mememberLegalRuleLogisticsMapper.delete(ruleLogistics.getId());
            }else if ( null !=ruleLogistics && ruleLogistics.getFreightMode()==2){
                mememberLegalRuleLogisticsMapper.delete(ruleLogistics.getId());
                mememberLegalLogistics.deleteByRuleLogisticsId(ruleLogistics.getId());
            }
        }
        result.setCode("0000");
        return result;
    }

    @Override
    public RestResult editMemberPowerInfo(MememberLegalRuleRequest form) {
        AdminOperate admin = form.getAdminOperate();
        if(null != form){
            if(form.getId() !=null){
                //主表修改mem_member_legal_rule
                MememberLegalRule memberRequest = BeanUtil.copy(form, MememberLegalRule.class);
                memberRequest.setUpdater(admin.getOperator());
                memberRequest.setUpdateTime(new Date());
                mememberLegalRuleMapper.update(memberRequest);
            }
        }
        return RestResult.success(1);
    }

    @Override
    public PageResult<MememberLegalRule> queryStoreMemberLegalRuleList(MememberLegalRule mememberLegalRule, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        mememberLegalRule.setDeleteFlag(0);
        AdminOperate admin = mememberLegalRule.getAdminOperate();
        if (admin.getDeptType().getCode() == 1){
            mememberLegalRule.setDeptId(admin.getDeptId());
        }
        List<MememberLegalRule> list = mememberLegalRuleMapper.queryPage(startIndex, pageQuery.getLimit(), mememberLegalRule);
        long count = mememberLegalRuleMapper.queryPageCount(mememberLegalRule);

        list.forEach(items -> {
            RestResult<String> name = sysDeptApi.queryDeptNameById(items.getDeptId());
            items.setDeptId(admin.getDeptId());
            items.setDeptName(name.getData());
        });

        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }
}